package dao;

import java.util.List;

import org.hibernate.Query;

import bean.User;

public class UserDAOImpl extends UserDAO {

    /**
     * 获取排名
     * 支持量大于count的数量
     * @param count
     * @return
     */
    public int getRank(int support) {
        String sql = "select count(user_id) from user where support > ?";
        Query query = getCurrentSession().createSQLQuery(sql).setInteger(0, support);
        return  ((Number) query.uniqueResult()).intValue();
    }

    /**
     * 投票
     * @param candidate
     */
    public void addSupport(String candidate) {
        String sql = "update user set support = support + 1 where open_id = ?";
        Query query = getCurrentSession().createSQLQuery(sql).setString(0, candidate);
        query.executeUpdate();
    }

    /**
     * 查询用户总数
     * @param queryKey 模糊查询关键字
     * @return         在某关键字下查询到的用户总数
     */
    public int queryCount(String queryKey) {
        String sql = "select count(user_id) from user where user_name like ?";
        Query query = getCurrentSession().createSQLQuery(sql).setString(0, "%" + queryKey + "%");
        return  ((Number) query.uniqueResult()).intValue();
    }

    /**
     * 用户投票排行榜
     * @param queryKey 模糊查询关键字
     * @param limit    每页数量
     * @param offset   偏移量（页数*每页数量）
     * @return         排行榜（用户信息）
     */
    public List<User> query(String queryKey, int limit, int offset) {
        log.debug("finding User instance with queryKey: " + queryKey
                + ", limit: " + limit + ", offset: " + offset);
        try {
            String queryString = "from User as model where model.userName like ? order by model.support desc, model.userId asc";
            Query queryObject = getCurrentSession().createQuery(queryString);
            queryObject.setParameter(0, "%" + queryKey + "%").setFirstResult(offset).setMaxResults(limit);
            return queryObject.list();
        } catch (RuntimeException re) {
            log.error("find by queryKey failed", re);
            throw re;
        }
    }
    
    public void updateUserInfoByOpenId(String openId, String userName, String headImgUrl){
        String sql = "update user set user_name = ?, avatar = ?  where open_id = ?";
        Query query = getCurrentSession().createSQLQuery(sql).setString(0, userName).setString(1, headImgUrl).setString(2, openId);
        query.executeUpdate();
    }

}
